; (() => {
    const oList = document.getElementById('list')
    const msg = document.getElementById('message')
    const oSend = document.getElementById('send')
    const ws = new WebSocket('ws:localhost:8000')
    let username = ''
    function init() {
        bindEvent()
    }
    function bindEvent() {
        oSend.addEventListener('click', btnHandle, false)
        ws.addEventListener('open', openHandle, false)
        ws.addEventListener('close', closeHandle, false)
        ws.addEventListener('error', errorHandle, false)
        ws.addEventListener('message', msgHandle, false)
        ws.addEventListener('connection', connectionHandle, false)
    }

    function btnHandle() {
        ws.send(JSON.stringify({
            username: username,
            date: new Date().getTime(),
            msg: msg.value
        }))
        msg.value = ''

    }

    function openHandle(e) {
        console.log('open', e);
        username = localStorage.getItem('username')

    }
    function closeHandle(e) {
        console.log('close', e);
    }
    function errorHandle(e) {
        console.log('error', e);
    }
    function msgHandle(e) {
        data = JSON.parse(e.data)
        console.log('message', JSON.parse(e.data));
        const oItem = document.createElement('li')
        oItem.innerHTML = `
            <p>
                <span>${data.username}</span>
                <i>${new Date(data.date)}</i>
            </p>
            <p>消息：${data.msg}</p>
        `
        oList.appendChild(oItem)
    }
    function connectionHandle(e) {
        console.log('connection', e);
    }

    init()
})();